package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.factories.ConnectionHandlerFactory;

import net.wimpi.modbus.io.ModbusTCPTransport;

public class ModbusServer implements Runnable{
	private int port;
	private ConnectionHandlerFactory handlerfactory;
	
	@SuppressWarnings("unused")
	@Override
	public void run(){
		ServerSocket s = null;
		try {
			s = new ServerSocket(port);
			while(true){
				try {
					
					Socket incoming = s.accept();
				    Thread deviceThread = new Thread(handlerfactory.create(new ModbusTCPTransport(incoming)));
				    deviceThread.start();
				    
				} catch (IOException e) {
				}
			}
		} catch (IOException e) {
			
		}
		if(s!=null)	try {
			s.close();
		} catch (IOException e) {}
	}

	/**
	 * @return the port
	 */
	public int getPort() {
		return port;
	}

	/**
	 * @param port the port to set
	 */
	public void setPort(int port) {
		this.port = port;
	}

	/**
	 * @return the handlerfactory
	 */
	public ConnectionHandlerFactory getHandlerfactory() {
		return handlerfactory;
	}

	/**
	 * @param handlerfactory the handlerfactory to set
	 */
	public void setHandlerfactory(ConnectionHandlerFactory handlerfactory) {
		this.handlerfactory = handlerfactory;
	}


}
